/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.lis.ctrl.actor;

import akka.actor.ActorRef;
import akka.actor.UntypedActor;
import com.cxhd.lis.DataCache;
import com.cxhd.lis.model.newmodel.LisResult;
import com.cxhd.lis.util.HttpClientUt;

import com.google.common.io.Files;
import com.google.gson.Gson;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

/**
 *
 * @author Administrator
 */
public class SendDataActor extends UntypedActor {

    private Record info = null;
    private List<Record> result = null;
    private String lis_samplecollection = null;

    @Override
    public void onReceive(Object o) throws Exception {
        try {
            lis_samplecollection = (String) o;
            //保存数据到lis_result
            saveToLisResult(lis_samplecollection);

            //是否发送到融合平台
            if (DataCache.getIntance().getConfig().get("medicalInfo_ip") != null || DataCache.getIntance().getConfig().get("hisDbFlag").equalsIgnoreCase("true")) {

                getPatInfo(lis_samplecollection);
                getResult();
                sendData();
                sendFinish();
            }
        } catch (Exception e) {
            sendFinish();
            e.printStackTrace();
        }

    }

    public void getPatInfo(String sample_info_id) {
        String sql = " select a.CHECKTIME as datetime,a.SAMPLENO AS sample_no, a.BARCODE,a.UUID AS update_id, b.PATIENTNAME AS name,b.PATIENTID AS info_id,b.SEX AS sex,b.AGE AS age,b.PHONENO AS phone,b.CARD_NO AS card_no,b.MEDICAL_NO AS medical_no, b.BIRTHDAY as birth, b.ADDRESS AS address,"
                + "   a.UUID,a.STAYHOSPITALMODE as patient_type,a.SECTION as department ,a.CHECKOPERATOR as doctor "
                + "from lis_samplecollection a left join lis_patient b on a.INFOPK = b.PK WHERE a.PK=" + sample_info_id;
        System.out.println(sql);
        info = Db.findFirst(sql);
    }

    public void getResult() {
        if (info != null && info.get("UUID") != null) {

            String sql = "select a.SAMPLENO AS sample_no, a.TESTID AS item_code,a.TESTRESULT as test_value,a.MEASURETIME as date_test,a.UNIT AS text_danwei,b.CHINESENAME AS item_name,c.MREFLO0 as low,c.MREFHI0 as high "
                    + " from lis_testresult a left join lis_testdescribe b on a.ITEMPK=B.PK LEFT JOIN lis_referencevalue c ON b.TESTID=c.TESTID where a.UUID='" + info.get("UUID") + "' and RESULTFLAG=0";
            // System.out.println("-------------------" + sql);
            sql = "select Sample_No AS sample_no, Item_Code AS item_code,Test_Value as test_value,Date_Test as date_test,Text_Danwei AS text_danwei,Item_Name AS item_name,Low as low,High as high,Text_Note as text_note"
                    + " from lis_result where uuid='" + info.get("UUID") + "' and data1='0'";
            result = Db.find(sql);

        }
    }

    public void sendData() {

       
        if (DataCache.getIntance().getConfig().get("medicalInfo_ip") != null && DataCache.getIntance().getConfig().get("medicalInfo_ip").length() > 5) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("patientInfo", JsonKit.toJson(info)));
            params.add(new BasicNameValuePair("result", JsonKit.toJson(result)));
            params.add(new BasicNameValuePair("hospital_code", DataCache.getIntance().getLocalhostSN()));

            String returnData = HttpClientUt.httpPost("http://" + DataCache.getIntance().getConfig().get("medicalInfo_ip") + "/MedicalInfo/patient/lisDetailByCxLis", params);
            if (returnData.equalsIgnoreCase("true")) {
                sendSuccess();
            }
        }
         saveToHis();
    }

    public void sendSuccess() {
        Db.update("update lis_samplecollection set UPDATE_STATUS = 1 where PK=" + lis_samplecollection);

    }

    public void sendFinish() {
        lis_samplecollection = null;
        info = null;
        result = null;
    }

    public void saveToHis() {
        try {
            System.out.println(DataCache.getIntance().getConfig().get("hisDbFlag"));
            if (DataCache.getIntance().getConfig().get("hisDbFlag").equalsIgnoreCase("true") && info.get("BARCODE") != null) {
                //String barcode = info.get("BARCODE");
                for (Record re : result) {
                    float res = checkNum(re.get("test_value") + "");
                    String text_node = "";
                    if (res != 0 && res != 0.0 && re.get("low") != null) {
                        if (res < Float.parseFloat(re.get("low") + "")) {
                            text_node = "↓";
                        } else if (res > Float.parseFloat(re.get("high") + "")) {
                            text_node = "↑";
                        }
                    }
                    String fw = re.get("low") + "--" + re.get("high");
                    if(re.get("low")==null){
                        fw ="";
                    }
                    String sql = "insert into Ut_Lis_result (Date_Test,Sample_No,Item_Code,Item_Name,Test_Value,Text_Range,Text_Danwei,Text_Note) VALUES ('"+re.get("date_test")+"','" + info.getStr("BARCODE") + "','" + re.get("item_code") + "','" + re.get("item_name") + "','" + re.get("test_value") + "','" + fw + "','" + re.get("text_danwei") + "','" + text_node + "')";
                     System.out.println(sql);

                    Db.use("hisdb").update(sql);

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public float checkNum(String s) {

        try {

            return Float.parseFloat(s);

        } catch (NumberFormatException e) {
            return 0;
        }
    }

    private void saveToLisResult(String lis_samplecollection) {

        try {
            Record info = Db.findFirst("select * from lis_samplecollection where PK=" + lis_samplecollection);

            if (info != null) {
                Db.update("delete from lis_result where uuid='" + info.get("UUID") + "'");
                //List<Record> list = Db.find("select a.SAMPLENO,a.ITEMPK,a.TESTID,a.TESTRESULT,a.DEVICEID,a.MEASURETIME,a.UUID,a.UNIT,b.CHINESENAME,c.MREFHI0,c.MREFLO0 from lis_testresult a left join lis_testdescribe b on a.ITEMPK=B.PK LEFT JOIN lis_referencevalue c ON b.TESTID=c.TESTID where a.UUID='" + info.get("UUID") + "' ");
                List<Record> list = Db.find("select a.RESULTFLAG,a.SAMPLENO,a.ITEMPK,a.TESTID,a.TESTRESULT,a.DEVICEID,a.MEASURETIME,a.UUID,c.UNIT,b.CHINESENAME,c.MREFHI0,c.MREFLO0 from lis_testresult a left join lis_testdescribe b on a.ITEMPK=B.PK LEFT JOIN pp_device_test c ON a.TESTID=c.TESTID and c.DEVICEID=a.DEVICEID  where a.UUID='" + info.get("UUID") + "' ");

                if (list != null && !list.isEmpty()) {
                    for (Record re : list) {

                        float res = checkNum(re.get("TESTRESULT") + "");
                        String text_node = "";
                        if (res != 0 && res != 0.0 && re.get("MREFLO0") != null) {
                            if (res < Float.parseFloat(re.get("MREFLO0") + "")) {
                                text_node = "↓";
                            } else if (res > Float.parseFloat(re.get("MREFHI0") + "")) {
                                text_node = "↑";
                            }
                            re.set("Text_Note", text_node);
                        }
                        new LisResult().saveOne(re);
                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
